package com.songshuai.sales.client.service.impl;

import com.songshuai.sales.client.constant.CacheKeys;
import com.songshuai.sales.client.constant.SalesClientConstant;
import com.songshuai.sales.client.feign.PanguApiClient;
import com.songshuai.sales.client.service.SalesMeetingService;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.QueryCustomersReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.SendInvitationReqDto;
import com.songshuai.webapi.baseapi.dto.feign.request.pangu.salemeeting.TalkNotesReqDto;
import com.songshuai.webapi.baseapi.dto.feign.response.pangu.salemeeting.*;
import com.songshuai.webapi.baseapi.enumerations.ResultStatus;
import com.songshuai.webapi.baseapi.pojo.BaseParmDto;
import com.songshuai.webapi.baseapi.pojo.QueryPageRes;
import com.songshuai.webapi.baseapi.pojo.QueryResponse;
import com.songshuai.webapi.baseapi.utils.DateUtil;
import com.songshuai.webapi.common.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @Author: lhx
 * @Date: 2019/3/23 14:19
 */
@Service
public class SalesMeetingServiceImpl implements SalesMeetingService {


    @Autowired
    private PanguApiClient panguApiClient;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 查询会议列表
     * @param type 0-最近 1-未来
     * @param userId 当前登陆用户id
     * @return
     */
    @Override
    public QueryResponse<List<MeetingListResDto>> queryMeetingList(Integer type, String userId) {
        QueryResponse<List<MeetingListResDto>> listQueryResponse = panguApiClient.queryMeetingList(type, userId);
        if (null != listQueryResponse){
            return listQueryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 根据会议查询客户集合
     * @param userId 当前登陆人
     * @param code 会议编号
     * @return
     */
    @Override
    public QueryResponse<List<CustomerListResDto>> queryCustomerList(String userId, String code) {
        QueryResponse<List<CustomerListResDto>> listQueryResponse = panguApiClient.queryCustomerList(userId, code);
        if (null != listQueryResponse){
            List<CustomerListResDto> data = listQueryResponse.getData();
            if (!CollectionUtils.isEmpty(data)){
                //由于盘古不存储是否接待状态，所以这里从缓存中取
                Map<Object, Object> hmgetMap = redisUtil.hmget(CacheKeys.MEETING_IS_RECEPTION_KEY+code);
                if (!CollectionUtils.isEmpty(hmgetMap)){
                    data.forEach(x -> {
                        if (hmgetMap.containsKey(x.getCustomerGuid())){
                            x.setIsReception((Boolean) hmgetMap.get(x.getCustomerGuid()));
                        }else {
                            //如果未查询到，并且客户出席状态为已出席，则认为未接待
                            if (SalesClientConstant.MEETING_ATTEND_STATUS_ALREADY.equals(x.getAttendStatus())) {
                                hmgetMap.put(String.valueOf(x.getCustomerGuid()), false);
                                x.setIsReception(false);
                            }else {
                                hmgetMap.put(String.valueOf(x.getCustomerGuid()), true);
                                x.setIsReception(true);
                            }
                            redisUtil.hmset(CacheKeys.MEETING_IS_RECEPTION_KEY + code, hmgetMap, DateUtil.getRemainSecondsOneDay(new Date()));
                        }
                    });

                }else {//未获取到，证明是当天第一次查询，如果是已出席状态，则客户默认未接待
                    Map<Object, Object> dataMap = new HashMap<>();
                    data.forEach(x -> {
                        if (SalesClientConstant.MEETING_ATTEND_STATUS_ALREADY.equals(x.getAttendStatus())){
                            dataMap.put(x.getCustomerGuid(),false);
                            x.setIsReception(false);
                        }else {
                            dataMap.put(x.getCustomerGuid(),true);
                            x.setIsReception(true);
                        }
                    });
                    redisUtil.hmset(CacheKeys.MEETING_IS_RECEPTION_KEY+code, dataMap, DateUtil.getRemainSecondsOneDay(new Date()));
                }
            }

            return listQueryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 查看邀请函
     * @param code 会议编号
     * @return
     */
    @Override
    public QueryResponse<List<InvitationLetterResDto>> queryInvitationLetter(String code) {
        QueryResponse<List<InvitationLetterResDto>> stringQueryResponse = panguApiClient.queryInvitationLetter(code);
        if (null != stringQueryResponse){
            return stringQueryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 查询客户信息
     * 邀约客户，根据姓名或手机号模糊查询
     * @return
     */
    @Override
    public QueryResponse<QueryPageRes<List<CustomerInfosResDto>>> queryCustomers(BaseParmDto<QueryCustomersReqDto> request) {
        QueryResponse<QueryPageRes<List<CustomerInfosResDto>>> listQueryResponse = panguApiClient.queryCustomers(request);
        if (null != listQueryResponse){
            return listQueryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 发送邀请函
     * @return
     */
    @Override
    public QueryResponse sendInvitation(SendInvitationReqDto request) {
        QueryResponse queryResponse = panguApiClient.sendInvitation(request);
        if (null != queryResponse){
            return queryResponse;
        }
        return new QueryResponse<>(ResultStatus.FAILOfficial);
    }


    /**
     * 查看客户回执单信息
     * @param inviteNo 邀约编号
     * @return
     */
    @Override
    public QueryResponse<ReceiptInfoResDto> queryReceipt(String inviteNo) {
        QueryResponse<ReceiptInfoResDto> queryResponse = panguApiClient.queryReceipt(inviteNo);
        if (null != queryResponse){
            return queryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 接待客户
     * @param code 会议编号
     * @param customerId 客户id
     * @return
     */
    @Override
    public QueryResponse<Boolean> receptionCustomer(String userId, String code, Long customerId) {

        Map<Object, Object> hmgetMap = redisUtil.hmget(CacheKeys.MEETING_IS_RECEPTION_KEY+code);
        if (CollectionUtils.isEmpty(hmgetMap)){
            hmgetMap = new HashMap<>();
        }
        hmgetMap.put(customerId,true);
        redisUtil.hmset(CacheKeys.MEETING_IS_RECEPTION_KEY+code, hmgetMap, DateUtil.getRemainSecondsOneDay(new Date()));
        return QueryResponse.setResData(true);
    }

    /**
     * 查询销售人员信息
     * @param userId
     * @return
     */
    @Override
    public QueryResponse<List<SalesManInfoResDto>> querySalesInfo(String userId) {
        QueryResponse<List<SalesManInfoResDto>> listQueryResponse = panguApiClient.querySalesInfo(userId);
        if (null != listQueryResponse.getCode()){
            return listQueryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }

    /**
     * 转交客户
     * @param userId 当前用户id
     * @param cluesId 客户id
     * @param saleId 转交销售id
     * @return
     */
    @Override
    public QueryResponse<Boolean> handOverCustomer(String userId, Long cluesId, Integer saleId) {
        QueryResponse<Boolean> queryResponse = panguApiClient.handOverCustomer(userId, Arrays.asList(cluesId), Arrays.asList(saleId));
        if (null != queryResponse){
            return queryResponse;
        }
        return new QueryResponse<>(ResultStatus.FAILOfficial);
    }

    /**
     * 新增沟通记录
     * @return
     */
    @Override
    public QueryResponse<Boolean> talkNotes(TalkNotesReqDto request) {
        QueryResponse queryResponse = panguApiClient.talkNotes(request);
        if (null != queryResponse){
            return queryResponse;
        }
        return new QueryResponse<>(ResultStatus.ERROR_CREATE_FAILED);
    }


    /**
     * 获取客户历史沟通记录
     * @param clueGuid
     * @return
     */
    public QueryResponse<CommunicateListResDto> getCommunicateList(Long clueGuid) {
        QueryResponse<List<CommunicateListResDto>> communicateList = panguApiClient.getCommunicateList(clueGuid);
        if (null != communicateList){
            if (!CollectionUtils.isEmpty(communicateList.getData())){
                return QueryResponse.setResData(communicateList.getData().get(0));
            }
            return new QueryResponse<>();
        }
        return new QueryResponse<>(ResultStatus.ERROR_SEARCH_FAILED);
    }


}
